  //Define global variable
  statusString = ['Open','Assigned','Closed']; // Training Status
  workArea = null; // Training of current selected
  currentId = null; // Id of current selected Training
  trainingDataset = null; // Training data pool
  skill = null; // Skill data
  pageNo = 1; // Current Page Number
  pageSize = 10; // Page size
  totalPageNum = 0; // Total page number

// Load Skill and SkillBranch from Server
function getSkillAndSkillBranch(){
  $.getJSON(applicationRoot + "/training/web/GetSkillAndSkillBranch.do",
           {},
       function callback(json){   
             skill = json.data;
             
             for(var i=0; i<skill.length; i++){
               $('#searchSkillName').append('<option value="' +skill[i].name+'">' + skill[i].name + '</option>');
             }          
       }); 
}

// For clicking update
function updateClicked(node){ 
  // Setup current id
  var id = node.id.replace('update','');
  currentId = id;
  
  // switch UI to editable mode
  switchToEditableMode(currentId);
}

// For clicking cancel
function cancelClicked(node){ 
    // Setup current id
    var id = node.id.replace('cancel','');
    currentId = id;
    
    // switch UI to noneditable mode
    switchToNonEditableMode(currentId);
  }

function saveClicked(node){ 
  // Setup current id
  var id = node.id.replace('save','');
  currentId = id;
  
  var newStatus = $('#statusList' + currentId).val();
  var oldStatus = trainingDataset[currentId].status;
  
  // Check whether it's need to update
  if(newStatus == oldStatus){
    alert('No need to update!');
    switchToNonEditableMode(currentId);
    return;
  }

  // Prepare info to update the status of current selected Training
  var data = {'id':trainingDataset[currentId].id, 'status':newStatus};
  // Send update info to remote server
  updateTrainingToServer(data);
  
  updateSelectList(id, newStatus);
}

// Switch UI to editable mode
function switchToEditableMode(id){

  $('#update' + id).hide();
  $('#statusLabel' + id).hide();
  
  $('#save' + id).show();
  $('#cancel' + id).show();
  $('#statusList' + id).show();
}

// Switch UI to non-editable mode
function switchToNonEditableMode(id){
  $('#update' + id).show();
  $('#statusLabel' + id).show();
  
  $('#cancel' + id).hide();
  $('#save' + id).hide();
  $('#statusList' + id).hide();
}

// Send update info to remote server
function updateTrainingToServer(data){
  // Setup workare to the data needed to be process
  workArea = data;
  
  $.getJSON(applicationRoot + "/training/web/updateTraining.do",
	         data,
			 function callback(json){// Callback function
               // Popup message
	           showUpdateFeedbackMessage(json.message);

               if(json.isSuccess == true){// If everything is fine
                 // Update state
                 trainingDataset[currentId].status = workArea.status;
                 $('#statusLabel' + currentId).text(statusString[trainingDataset[currentId].status]);
                 $('#statusValue' + currentId).val(trainingDataset[currentId].status);
                 
                 // Switch UI
                 switchToNonEditableMode(currentId);
               }else{// Handle error
               
                 // restore state
            	 var orgStatus = trainingDataset[currentId].status;
            	 $('#statusList' + currentId).val(orgStatus);
            	 $('#statusLabel' + currentId).text(statusString[orgStatus]);
               }   
                                         
               // Switch UI to non-editable state
               switchToNonEditableMode(currentId);
	         }); 
}

// Load Training data from server
function loadDataFromServer(requestData){
    
	$.ajax({
      url:applicationRoot + '/training/web/getAllTraining.do',
      type:'post', 
      dataType:'json', 
      data:requestData,
      success:function(json){ 	
       	 if(json.isSuccess == true){// If everything is fine
      	   trainingDataset = json.data;
           pageNo = 1;
      	   populateTrainingTable(trainingDataset);
           totalPageNum = Math.ceil(trainingDataset.length/pageSize);
//           $('#totalPage').text(totalPageNum);
//           $('#totalRecord').text(trainingDataset.length);
           updatePageBox();
      	 }else{// Handle errors
          trainingDataset = [];
          totalPageNum = 0;
          populateTrainingTable(trainingDataset);
      	  alert(json.message);
           }
       },
       error:function (json){// Handle errors
          alert('Remote service is not available!');
           }
	});	  
}

function populateTrainingTableRow(data, id){
    // Create row from template
    $('#trainingTableBody').append("<tr>" + $('#trTemplate').html().replace(/%%/g, id) + "</tr>");
    
    // Setup data
    $('#userName' + id).text(data.userName);
    $('#gradeName' + id).text(data.gradeName);
    $('#statusLabel' + id).text(statusString[data.status]);
    $('#statusValue' + id).val(data.status);
    $('#statusList' + id).val(data.status);
    $('#skillName' + id).text(data.skillName);
    $('#skillBranchName' + id).text(data.skillBranchName);
    $('#instruction' + id).text(data.instruction);
    $('#creator' + id).text(data.creator);
    $('#cdd' + id).text(data.cDate.substring(0, 10));
    
    // Groups need to be transformed
    var groups = '';
    for(var i=0; i<data.groups.length; i++){
      groups = groups + data.groups[i];
      
      if(i < (data.groups.length - 1)){
        groups += ', ';
      }
    }
    
    $('#groupName' + id).text(groups);
    
    updateSelectList(id, data.status);
}


function updateSelectList(id, status){
  var selectControl = $('#statusList' + id);
  
  selectControl.find('option').each(function(i) {
      $(this).remove();
   });
	
  for(var i=status; i <=2 ; i++){
	selectControl.append('<option value="'+i+'">'+statusString[i]+'</option>');
    
	if((i - status) >= 1 ){
      break; // Only one step in one update
    }
  }
}

// Populate data table with data
function populateTrainingTable(data){
  cleanTableRow();

  if(data.length == 0){
	  $('#noDataNotice').show();
  }else{
    $('#noDataNotice').hide();
  }
  
  var start = (pageNo-1)*pageSize;
  var end = pageNo*pageSize;
  
  if(end > trainingDataset.length){
    end = trainingDataset.length;
  }
  
  if(start < 0){
    start = 0;
  }
  for(var i=start; i<end; i++){
	populateTrainingTableRow(data[i], i);
  } 

  gridColor();
  $("#trainingTable").trigger("update");

}

function showNoDataNotice(){
 
}

function cleanTableRow(){
	 $("#trainingTableBody").find("tr").not(":has(th)").each(function(i) {
	     $(this).remove();
	 });
}

function submitSearch(){
	
  $("#notice").hide(); 
	 
  var requestData = {
    userName:$('#searchUerName').val(),
	groupName:$('#searchGroupName').val(),
    gradeName:$('#searchGradeName :selected').val(),
	from:$('#searchFrom').val(),
	to:$('#searchTo').val(),
	status:$('#searchStatus').val(),
	skillName:$('#searchSkillName :selected').val(),
	skillBranchName:$('#searchSkillBranchName :selected').val()
  }
  
  loadDataFromServer(requestData);
}

function resetSearch(){
	$('#searchUerName').val('');
	$('#searchGroupName').val('');
    $('#searchGradeName').val('');
    $('#searchStatus').val(-1);
	$('#searchFrom').val('');
	$('#searchTo').val('');
	$('#searchGradeName').val('');
	$('#searchStatus').val('');
	$('#searchSkillName').val('');
	$('#searchSkillBranchName').val('');
    clearupSkillBranchList();
    
    //Hide Notice
    $("#notice").hide(); 
}

function onStatusChanged(node){
  var id = node.id.replace('statusList','');
  var nodeObj = $(node);
  
  var orNum = Number($('#statusValue' + id).val());
  var newNum = Number(nodeObj.val());
  
  if(orNum < newNum){
    nodeObj.val(2);
  }
  
}

// Open user search help window, it search users using userName, returns users
  function openUserWin(){
    var userName = $('#searchUerName').val();
    userName = window.showModalDialog(applicationRoot + "/Pages/Jsp/Report/userSearchHelp.jsp", userName,
        "dialogHeight:500px;dialogWidth:640px;dialogLeft:150px;dialogTop:150px;status=off;scroll=yes;resizeable=yes");
    $('#searchUerName').val(userName);
  }

  // Open group search help window, it search groups using groupName, returns
	// groups
  function openGroupWin(){
    var groupName = $('#searchGroupName').val();
    groupName = window.showModalDialog(applicationRoot + "/Pages/Jsp/Report/groupSearchHelp.jsp", groupName,
        "dialogHeight:500px;dialogWidth:640px;dialogLeft:150px;dialogTop:150px;status=off;scroll=yes;resizeable=yes"); 
    $('#searchGroupName').val(groupName);
  }
  
  function refreshSkillBranch(){
    var name = $('#searchSkillName :selected').val();

    if(name == null || name ==''){
      clearupSkillBranchList();
      return;
    }
    
    var tempSkill = getSkillByName(name);
    var sbs = tempSkill.skillBranches;
    
    clearupSkillBranchList();
   
    for(var i=0; i < sbs.length; i++){
      $('#searchSkillBranchName').append('<option value="' + sbs[i].name + '">' + sbs[i].name + '</option>');
    }
  }
  
  function getSkillByName(name){
    for(var i=0; i<skill.length; i++){
      if(skill[i].name == name){
        return skill[i];
      }
    }
    
    return null;
  }
  
  function clearupSkillBranchList(){
    $('#searchSkillBranchName').find('option').each(function(i) {
       $(this).remove();
    });
    
    $('#searchSkillBranchName').append('<option value="">--Please Select--</option>');
  }
  
  function goFirst(){
    pageNo = 1;
    populateTrainingTable(trainingDataset);
  }
  
  function goLast(){
    pageNo = totalPageNum;
    populateTrainingTable(trainingDataset);  
    
    updatePageBox();    
  }
  
  function goPre(){
    if(1 < pageNo){
      pageNo--;
      populateTrainingTable(trainingDataset);
    }else{
      alert('No previous Page!');
    }
    
    updatePageBox();    
  }
  
  function goNext(){
    var dataSize = trainingDataset.length;
    if(totalPageNum > pageNo){
      pageNo++;
      populateTrainingTable(trainingDataset);
    }else{
      alert('No next Page!');
    }

    updatePageBox();
  }
  
  function goTo(){
    
    var target = $('#goTo').val();
    
    if(0 < target && totalPageNum >= target){
      pageNo = target;
      populateTrainingTable(trainingDataset);
    }else{
      alert('Please check the input');
    }
    
    updatePageBox();
  }
  
  function showUpdateFeedbackMessage(msg){
	  
	$('#feedbackMessage').text(msg);  
    
	$("#notice").show(); 
    
    /*setTimeout(function(){
      $("#notice").fadeOut('slow');
    },1000);*/
  
  }
  
  function updatePageBox(){
	if(totalPageNum <= 0){
	  $('#pageBox').val('0/0');
	}else{
      $('#pageBox').val( pageNo + '/' + totalPageNum);
	}
  }